﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;
using System.IO.Ports;
using System.Text;
using System.Threading; 


namespace PosPrinter
{
    public class POSPrinter
    {
        const int OPEN_EXISTING = 3; 
        string prnPort = "LPT1"; 
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)] 
        private static extern IntPtr CreateFile(string lpFileName, 
        int dwDesiredAccess, 
        int dwShareMode, 
        int lpSecurityAttributes, 
        int dwCreationDisposition, 
        int dwFlagsAndAttributes, 
        int hTemplateFile); 

        public POSPrinter() 
        { 
            //  
            //  TODO:  在此处添加构造函数逻辑  
            //  
        } 
        public POSPrinter(string prnPort) 
        { 
            this.prnPort = prnPort;//打印机端口  
        }
        public string PrintLine(string str)
        {
            lock (this)//同步锁 
            {
                IntPtr iHandle = CreateFile(prnPort, 0x40000000, 0, 0, OPEN_EXISTING, 0, 0);
                if (iHandle.ToInt32() == -1)
                {
                    return "没有连接打印机或者打印机端口不是LPT1";
                }
                else
                {
                    str += "\n";

                    FileStream fs = new FileStream(iHandle, FileAccess.ReadWrite);
                    StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default);  //写数据 
                    //sw.WriteLine((((char)27).ToString()) + ((char)64).ToString()); //初始化打印机状态 
                    sw.WriteLine(str);
                    sw.Close();
                    fs.Close();
                    return "";
                }
            }
        }

        public string OpenBox()
        {
            return PrintLine(((char)27).ToString() + ((char)112).ToString() + ((char)0).ToString() + ((char)100).ToString() + ((char)100).ToString());
        }

    }
}
